/*
 * @lc app=leetcode.cn id=224 lang=javascript
 *
 * [224] 基本计算器
 */

// @lc code=start
/**
 * @param {string} s
 * @return {number}
 */
var calculate = function (s) {
  // 存结果和符号
  const num_stack = [];
  const op_stack = [];
  let sign = 1;
  let res = 0;
  let i = 0;
  while (i < s.length) {
    const ch = s[i];
    if (/\d/.test(ch)) {
      let num = 0;
      while (i < s.length && /\d/.test(s[i])) {
        num = num * 10 + Number(s[i]);
        i++;
      }
      res += sign * num;
      continue;
    }
    if (ch === "+" || ch === "-") sign = ch === "+" ? 1 : -1;
    else if (ch === "(") {
      num_stack.push(res);
      op_stack.push(sign);
      res = 0;
      sign = 1;
    } else if (ch === ")") {
      res = num_stack.pop() + res * op_stack.pop();
    }
    i++;
  }
  return res;
};
// @lc code=end
